<template>
  <zz-Dialog
    v-model="open"
    @confirm="handleOk"
    @cancel="handleClose"
    :loading="loading"
    :title="title"
    :confirmButtonText="proxy.$t('common.confirm')"
    :cancelButtonText="proxy.$t('common.cancel')"
    :align-center="true"
    :size="'large'"
  >
    <el-container class="dialog-template-layout">
      <el-main>
        <zz-Form
          ref="rootForm"
          :rules="ruleValidate"
          :model="model"
          :readOnly="type === 'view'"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input
                  v-model="model.username"
                  placeholder="请输入用户名"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-select
                  v-model="model.gender"
                  placeholder="请选择性别"
                  clearable
                >
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="描述" prop="description">
                <el-input
                  v-model="model.description"
                  type="textarea"
                  placeholder="请输入描述"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期" prop="birthDate">
                <el-date-picker
                  v-model="model.birthDate"
                  type="date"
                  placeholder="请选择出生日期"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="创建时间" prop="createdDatetime">
                <el-date-picker
                  v-model="model.createdDatetime"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择创建时间"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="登录时间" prop="loginTime">
                <el-time-picker
                  v-model="model.loginTime"
                  value-format="HH:mm:ss"
                  placeholder="请选择登录时间"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="更新时间" prop="updatedAt">
                <el-date-picker
                  v-model="model.updatedAt"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择更新时间"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                <el-input-number
                  v-model="model.age"
                  :min="0"
                  :max="100"
                  :step="1"
                  :precision="0"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="总浏览次数" prop="totalViews">
                <el-input-number
                  v-model="model.totalViews"
                  :min="0"
                  :max="100"
                  :step="1"
                  :precision="0"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身高" prop="height">
                <el-input-number
                  v-model="model.height"
                  :min="0"
                  :max="100"
                  :step="0.01"
                  :precision="2"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="体重" prop="weight">
                <el-input-number
                  v-model="model.weight"
                  :min="0"
                  :max="100"
                  :step="0.01"
                  :precision="2"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="薪资" prop="salary">
                <el-input-number
                  v-model="model.salary"
                  :min="0"
                  :max="100"
                  :step="0.01"
                  :precision="2"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="本地值" prop="localeValue">
                <el-input
                  v-model="model.localeValue"
                  type="textarea"
                  placeholder="请输入本地值"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </zz-Form>
      </el-main>
    </el-container>
  </zz-Dialog>
</template>

<script setup>
import { computed, getCurrentInstance, ref, watch } from "vue";
const { proxy } = getCurrentInstance();

// props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
});

// emits
const emit = defineEmits(["update:modelValue", "query"]);

const open = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});

watch(
  open,
  (newValue, oldValue) => {
    if (newValue) {
      init();
      if (type.value !== "add") {
        queryById();
      }
    }
  },
  { immediate: true }
);

const loading = ref(false);
const title = ref("");
const type = ref("add"); // 表单模式，add新增，edit编辑，view查看

const genderList = ref([]);

// 表单
const rootForm = ref(null);

const model = ref({
  username: "",
  gender: "",
  description: "",
  birthDate: "",
  createdDatetime: "",
  loginTime: "",
  updatedAt: "",
  age: 0,
  totalViews: 0,
  height: 0,
  weight: 0,
  salary: 0,
  localeValue: "",
});

// 表单校验规则
const ruleValidate = ref({
  username: [{ required: true, message: "不能为空", trigger: "change" }],
});

// 初始化
const init = async () => {};

// 根据id查询
const queryById = async () => {
  if (!model.value.id) {
    return;
  }
  let res =
    await proxy.$API.testDataTypesManagement.testDataTypes.queryById.get(
      model.value.id
    );
  if (res.code === "01") {
    // 处理json格式数据
    if (res.data.localeValue) {
      res.data.localeValue = JSON.stringify(res.data.localeValue);
    }
    model.value = { ...res.data };
  } else {
    console.error(proxy.$t("common.queryFailed"), res);
  }
};

// 保存
const handleOk = async () => {
  let valid = await proxy.$refs.rootForm.validate();
  if (!valid) {
    return;
  }
  loading.value = true;
  let params = dealParams();
  if (model.value.id) {
    modify(params);
  } else {
    save(params);
  }
};

const dealParams = () => {
  let params = {
    ...model.value,
  };
  // todo: 处理特殊格式数据
  params["birthDate"] = proxy.$TOOL.format.formatDate(model.value["birthDate"]);
  params["createdDatetime"] = proxy.$TOOL.format.formatDateTime(
    model.value["createdDatetime"]
  );
  params["updatedAt"] = proxy.$TOOL.format.formatDateTime(
    model.value["updatedAt"]
  );
  if (model.value["localeValue"]) {
    params["localeValue"] = JSON.parse(model.value["localeValue"]);
  }
  return params;
};

// 新增
const save = async (params) => {
  let res = await proxy.$API.testDataTypesManagement.testDataTypes.save.post(
    params
  );
  if (res.code === "01") {
    proxy.$message.success(proxy.$t("message.addSuccess"));
    emit("query");
    handleClose();
    loading.value = false;
  } else {
    console.error(proxy.$t("message.addFailed"), res);
    loading.value = false;
  }
};

// 修改
const modify = async (params) => {
  if (!model.value.id) {
    return;
  }
  params.id = model.value.id;
  let res = await proxy.$API.testDataTypesManagement.testDataTypes.modify.post(
    params
  );
  if (res.code === "01") {
    proxy.$message.success(proxy.$t("message.modifySuccess"));
    emit("query");
    handleClose();
    loading.value = false;
  } else {
    console.error(proxy.$t("message.modifyFailed"), res);
    loading.value = false;
  }
};

// 更改
const changeGender = (value) => {};

// 关闭
const handleClose = () => {
  open.value = false;
  reset();
};

// 清除数据
const reset = () => {
  proxy.$refs.rootForm.resetFields();
  model.value = {
    id: "",
    username: "",
    gender: "",
    createdDatetime: null,
    updatedAt: null,
  };
};

defineExpose({ title, type, model });
</script>
